﻿#include"StashManageController.h"
#include"LoginController.h"
#include"MainController.h"
#include"StashManageModel.h"
#include"XQMySql.hpp"
#include"XQSettingsInfo.h"
#include"XQPortraitTreeDockWidget.h"
StashManageController::StashManageController(QObject* parent)
	:StashManageControllerObject(parent)
{
	init();
}

StashManageController::~StashManageController()
{
	//qDebug() << "主控制器释放";
}

LoginController* StashManageController::loginController() const
{
	return m_login;
}

MainController* StashManageController::mainController() const
{
	return m_main;
}

void StashManageController::openLogin()
{
	//首先登录
	if (m_login == nullptr)
	{
		m_login = new LoginController(this);
		m_login->copyModel(model());
		//m_login->model<StashManageModelObject>() = model<StashManageModelObject>();
		m_login->readLoginSettings();
		
		connect(m_login, &LoginController::loginSignals, this, &StashManageController::loginSlots);
		
		connect(m_login->loginView(), &QWidget::destroyed, [=] {if (m_main)m_main->view()->setEnabled(true); });
	}
	m_login->showView();
}

void StashManageController::openMain()
{
	if (m_main == nullptr)
	{
		m_main = new MainController(this);
		m_main->copyModel(model());
		QObject::connect(m_main, &MainController::requestLoginSignals,this,&StashManageController::requestLoginSlots);
		
	}
	m_main->view()->setEnabled(true);
}

void StashManageController::loginSlots(const XQUserData& user)
{
	//qDebug() << "登录";
	if (m_login)
	{
		m_login->deleteLater();
		m_login = nullptr;
	}
	model()->setUserData(user);
	model()->setUserState(UserState::Login);
	openMain();
	m_main->login(user);
}

void StashManageController::requestLoginSlots()
{
	openLogin();
	m_main->view()->setEnabled(false);
}


void StashManageController::init()
{
	setModel(new StashManageModel(nullptr,new XQMail(this), new XQSettingsInfo(this), new XQThreadQueuePool(this)));
	model()->setUserInfo(new XQUserInfo(this));
	auto task=model()->addMySqlThreadTask([this] {
		model()->setMySql(new XQMySql());
		connect(this, &QObject::destroyed, model()->mysql(), &QObject::deleteLater, Qt::QueuedConnection); 
		});
	model()->pool()->wait_event(task);
	model()->settings()->setSaveFile();

	//电子邮件设置

	auto mail = model()->mail();
	//邮箱smtp,如"smtp.126.com"
	mail->setServer("smtp.qq.com", 465);
	//邮箱账号名，如"****@126.com"
	mail->setUser("727370630@qq.com", "mjgidatejzqtbdjg");
	//发件人名字
	mail->setSender("Manage", "727370630@qq.com");


	//注册数据模型

	openLogin();
}
